package util.pref;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;

/**
 * This class implements the PrefInterface. It lets you access and store
 * preferences in a file. There are two methods, getPreferences - for
 * retrieving any number of preferences (the only thing you have to provide
 * is a String[] array with the corresponding keys), and setPreferences - 
 * to save any number of preferences (you only have to provide a hash map
 * with the key-value pairs to be saved.)
 * @author Robert
 */
public class PrefHandler implements PrefInterface {

    /**
     * the location of the preferences file
     */
    private String fileLocation = "versi.properties";

    public PrefHandler(String configfile) {
		fileLocation = configfile;
	}

	public PrefHandler() {
	}

	/**
     * Reads preferences from a file. Just provide the keys you want to read.
     * @param keys The key indicators of the key-value pairs in the file
     * @return An array of strings (in the same order as the provided keys)
     */
    public HashMap<String,String> getPreferences(String[] keys) {
        try {
            /**
             * initiating variables and loading preference file
             */
            Properties pref = new Properties();
            HashMap<String, String> hm = new HashMap<String, String>();
            pref.load(new FileInputStream(fileLocation));
            
            /**
             * iterating through provided array, taking the key, 
             * using it to get the value, saving both key and value in a
             * hash map
             */
            for (int i = 0; i < keys.length; i++) {
                hm.put(keys[i], pref.getProperty(keys[i]));
            }
            return hm;
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
            return null;
        }
    }

    /**
     * Saves preferences in a file. If a key-value pair does not exist, it
     * creates a new one in the file. If it does exist, it overwrites the old
     * value.
     * @param pairs A HashMap that contains the key-value pairs to be saved.
     * @return return True if saved successfully, false if not.
     */
    public Boolean setPreferences(HashMap<String, String> pairs) {
        if (!pairs.isEmpty()) {
            try {
                /**
                 * initializing all important variables and loading the 
                 * preference file
                 */
                Properties pref = new Properties();
                pref.load(new FileInputStream(fileLocation));
                Properties prefNew = new Properties();
                Iterator<?> iterator = pref.keySet().iterator();
                String key;
                String value;

                /**
                 * iterating through all properties and checking if we can 
                 * find one of its keys in the provided key-value pairs
                 * if we find one, we update its value
                 * if not, we save the existing value
                 */
                while (iterator.hasNext()) {
                    key = iterator.next().toString();
                    if (pairs.containsKey(key)) {
                        value = pairs.get(key).toString().trim();
                        pairs.remove(key);
                    } else {
                        value = pref.getProperty(key);
                    }
                    prefNew.put(key, value);
                }

                /**
                 * adding the new key pairs (which have not been in the file
                 * before
                 */
                if (!pairs.isEmpty()) {
                    Iterator<?> it = pairs.keySet().iterator();
                    while (it.hasNext()) {
                        key = it.next().toString();
                        value = pairs.get(key).toString().trim();
                        prefNew.put(key, value);
                    }
                }

                /**
                 * store all preferences in the properties file
                 */
                prefNew.store(new FileOutputStream(fileLocation), null);
                return true;
            } catch (IOException ex) {
                System.out.println("Could not save settings: " + ex.getMessage());
                return false;
            }
        } else {
            System.out.println("PrefHandler.setPreferences: Please provide keys and values!");
            return false;
        }
    }

	public HashMap<String, String> getAllPreferences() {
      try {
    	Properties pref = new Properties();
        HashMap<String, String> hm = new HashMap<String, String>();
        
        pref.load(new FileInputStream(fileLocation));
        Enumeration<Object> em = pref.keys();

        while(em.hasMoreElements()){
        	String str = (String)em.nextElement();
        	hm.put( str, (String) pref.get(str));
        }
        return hm;
      } catch (IOException ex) {
        System.out.println(ex.getMessage());
        return null;
      }
	}
    
//    public String getEntry(String key) {
//        try {
//        	Properties pref = new Properties();
//            pref.load(new FileInputStream(fileLocation));
//            return pref.getProperty(key);
//        } catch (IOException ex) {
//            System.out.println(ex.getMessage());
//            return null;
//        }
//    }
}
